package com.ruoyi.common.utils;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
import java.net.Socket;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

public class TCPSocketUtil {

    public static String GATEWAY_ID  = "gatewayId";//网关编码
    private static final int MAX_RETRIES = 3;

    /**
     * 发送数据
     */
    public static String sendData(String host, Integer port, String message) {
        boolean sent = false;
        int retries = 0;
        String response = "";

        while (!sent && retries < MAX_RETRIES) {
            try (Socket socket = new Socket(host, port);
                 PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
                 BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()))) {
                out.println(message);
                // 等待并读取响应
                response = in.readLine();
                if (!response.isEmpty()) {
                    sent = true;

                    System.out.println("消息发送成功: " + message);
                } else {
                    System.err.println("未能收到成功响应: " + message);
                }
            } catch (IOException e) {
                retries++;
                System.err.println("发送失败, 重试第" + retries + "次: " + message);
                if (retries >= MAX_RETRIES) {
                    System.err.println("重试次数超过最大重试次数，消息未发送: " + message);
                }
            }
        }
        return response;
    }

    /**
     * AES加密
     *
     * @param data      加密数据
     * @param secretKey 秘钥
     */
    public static String encrypt(String data, String secretKey) {
        try {
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey.getBytes(StandardCharsets.UTF_8), "AES");
            cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
            byte[] encrytedBytes = cipher.doFinal(data.getBytes(StandardCharsets.UTF_8));
            return Base64.getEncoder().encodeToString(encrytedBytes);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}
